﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Disassembler
{
    class CodeReaderClass : Reader
    {
        //начало секции данных
        private int _addrOfTableSection;
        private int _addrOfCode;
        //размер секции с кодом
        private int _sizeOfCode;
        //адрес секции с кодом
        private int _addrOfRawData;
        //всё содержимое PE-файла
        private string _data;

        public CodeReaderClass(string pathToData)
            : base(pathToData)
        {
            FileReaderClass fileReader = new FileReaderClass(PathToData);
            _data = fileReader.ReadData();
            ReadTableSection();
            //_data.ToCharArray();
        }

        private void ReadTableSection()
        {
            char[] buf = new char[8];
            string sbuf = "";

            _addrOfTableSection = _data.IndexOf(".text");
            _data.CopyTo(_addrOfTableSection, buf, 0, 8);

            UInt64 q;
            string w = CharArrayToString(buf);

            UInt64.TryParse(w, out q);
            sbuf = q.ToString("X");

            sbuf = ReadBinaryData(buf);

            if (int.TryParse(sbuf, out _sizeOfCode))
            {

                ;//all is good
            }
        }

        private string CharArrayToString(char[] buf)
        {
            string outStr = "";
            for (int i = 0; i < buf.Length; i++)
            {
                outStr += buf[i];
            }
            return outStr;
        }

        private string ReadBinaryData(char[] buf)
        {
            /*
            (ulong)(hex) 00 00 01 00 -> (hex)10000 -> (dec)65536
            */

            var parity = buf.Length % 2 == 0;
            if (parity)
            {
                string outString = "";
                string hexChar = "";
                for (int c = buf.Length - 2; c >= 0; c -= 2)
                {
                    outString += ((int)buf[c]).ToString("X");
                    outString += ((int)buf[c + 1]).ToString("X");
                }
                return outString;
            }
            else
            {
                throw new Exception("ReadBinaryData");
            }
        }

        private int SectionsTableAddr()
        {
            return 0;
        }
    }
}
